// pages/bind-house/bind-house.js
import req from "../../../utils/request"
Page({
  data: {
    // 房屋树形数据（含ID信息）
    houseTree: {},
    idTypeColumns: [], // 新增一个变量来存储 columns 的值
    residentTypeColumns: [], // 新增一个变量用于存储处理后的 columns 数据
    // 选择器配置
    houseColumns: [
      { values: [], className: 'column1' }, // 小区
      { values: [], className: 'column2' }, // 楼栋
      { values: [], className: 'column3' }, // 单元
      { values: [], className: 'column4' }, // 楼层
      { values: [], className: 'column5' }  // 房间
    ],
    formData: {
      community: "",
      communityId: "",
      building: "",
      buildingId: "",
      unit: "",
      unitId: "",
      floor: "",
      floorId: "",
      room: "",
      houseId: "",
      name: "",
      gender: "",
      phone: "13877667788",
      idType: "",
      idTypeId: "",
      idNumber: "",
      residentType: "",
      typeId: "",
      image: "", // 住户照片路径
      idImage: "" // 证件照片路径
    },
    photoList: [],
    idCardPhotoList: [], // 证件照片列表
    submitting: false,
    canSubmit: false,

    // 选择器状态
    showHousePicker: false,
    showGender: false,
    showIdType: false,

    // 选项数据
    roomOptions: [],
    genderOptions: ["男", "女"],
    
    // 证件类型选项（含映射ID）
    idTypeOptions: [],
    
    // 住户类型选项（含映射ID）
    residentTypeOptions: [],
    
    // 映射字典
    idTypeMap: {
      "身份证": "1",
      "护照": "2",
      "军官证": "3",
      "港澳通行证": "4"
    },
    residentTypeMap: {
      "业主": "1",
      "家属": "2",
      "租户": "3"
    },
    showResidentType: false, // 控制弹窗显示
    baseUrl: 'http://localhost:8080',
    uploadFileUrl: '/common/upload',
  },

  async onLoad() {
    // 获取房屋数据
    const apiData = await req.get("/property/community_house/list");
    const houseTree = this.buildHouseTree(apiData.data);
    this.setData({houseTree})
    this.checkCanSubmit()
    this.getResidentTypeOptions()
    this.getIdTypeOptions()
    this.setData({
      idTypeColumns: this.data.idTypeOptions.map(i => i.label),
      residentTypeColumns: this.data.residentTypeOptions.map(i => i.label)
    });
    
    // 初始化选择器第一列（小区）
    this.setData({
      'houseColumns[0].values': this.getCommunities(houseTree)
    });
  },

  // 获取小区列表（带ID）
  getCommunities(houseTree) {
    return Object.keys(houseTree).map(name => ({
      text: name,
      value: houseTree[name].id
    }));
  },

  // 字段变化处理
  onFieldChange(e) {
    const  field  = e.currentTarget.dataset.field
    const { value } = e.detail

    this.setData({
      [`formData.${field}`]: e.detail,
    })

    this.checkCanSubmit()
  },

  // 住户照片上传
  async onPhotoUpload(e) {
    const { file } = e.detail
    const { baseUrl, uploadFileUrl } = this.data;
    const token = wx.getStorageSync('token');
    // 模拟上传 - 实际项目中应替换为真实的文件上传API
    try {
      const res = await new Promise((resolve, reject) => {
        wx.uploadFile({
          url: baseUrl + uploadFileUrl,
          filePath: file.tempFilePath,
          name: 'file',
          header: {
            "Content-Type": "multipart/form-data",
            'Authorization': token ? `Bearer ${token}` : ''
          },
          success: resolve,
          fail: reject
        });
      });
      
      if (res.statusCode === 200) {
        const response = JSON.parse(res.data);
        if (response.code === 200) {
          // 构造文件对象
          const fileItem = {
            url: `http://localhost:8080${response.fileName}`, // 下载地址
            name: response.originalFilename, // 原始文件名
            status: 'done', // 上传状态
            message: '上传成功', // 状态提示
            // 如果需要预览，可以保留原始文件路径
            tempFilePath: file.tempFilePath,
            fileName:response.fileName
          };
          // 更新certificateFiles数组
          this.setData({
            "photoList": [fileItem],
            "formData.image": response.fileName
          });
          
          return {
            success: true,
            fileName: response.fileName,
            fileUrl: response.url,
            originalName: response.originalFilename
          };
        }
      }
      return { success: false, message: res.data };
    } catch (error) {
      console.error('上传失败:', error);
      return { success: false, message: '网络错误' };
    }
  },

  // 住户照片删除
  onPhotoDelete() {
    this.setData({
      photoList: [],
      'formData.image': ""
    })
  },

  // 证件照片上传
  onIdCardPhotoUpload(e) {
    const { file } = e.detail

    // 模拟上传 - 实际项目中应替换为真实的文件上传API
    const url = file.url || file.path;
    
    this.setData({
      idCardPhotoList: [
        {
          url: url,
          name: "证件照片",
          isImage: true,
        },
      ],
      'formData.idImage': url
    })
  },

  // 证件照片删除
  onIdCardPhotoDelete() {
    this.setData({
      idCardPhotoList: [],
      'formData.idImage': ""
    })
  },

    // 显示房屋选择器（改进版）
    showHousePicker() {
      const { houseTree } = this.data;
      const communities = this.getCommunities(houseTree);
  
      if (communities.length === 0) {
        wx.showToast({ title: '暂无房屋数据', icon: 'none' });
        return;
      }
  
      this.setData({
        showHousePicker: true,
        houseColumns: [
          { values: communities, className: 'column1' },
          { values: [], className: 'column2' },
          { values: [], className: 'column3' },
          { values: [], className: 'column4' },
          { values: [], className: 'column5' }
        ]
      }, () => {
        // 在setData回调中确保DOM已更新
        this.autoExpandHousePicker();
      });
    },
  
    // 自动展开房屋选择器所有层级
    autoExpandHousePicker() {
      const { houseTree } = this.data;
      const picker = this.selectComponent('#housePicker');
      if (!picker) return;
  
      // 获取第一列数据
      const communities = this.getCommunities(houseTree);
      if (communities.length === 0) return;
  
      // 模拟完整选择路径
      const community = communities[0];
      const communityName = Object.keys(houseTree).find(name => houseTree[name].id === community.value);
      
      // 楼栋数据
      const buildings = houseTree[communityName].buildings.map(b => ({
        text: b.name,
        value: b.id
      }));
      if (buildings.length === 0) return;
  
      // 单元数据
      const building = houseTree[communityName].buildings.find(b => b.id === buildings[0].value);
      const units = (building.units || []).map(u => ({
        text: u.name,
        value: u.id
      }));
      
      if (units.length === 0) return;
      // 楼层数据
      const unit = building.units.find(u => u.id === units[0].value);
      const floors = (unit.floors || []).map(f => ({
        text: f.name,
        value: f.id
      }));
      if (floors.length === 0) return;
  
      // 房间数据
      const floor = unit.floors.find(f => f.id === floors[0].value);
      const rooms = (floor.rooms || []).map(r => ({
        text: r.name,
        value: r.id
      }));
  
      // 一次性设置所有列的值
      picker.setColumns([
        { values: communities, className: 'column1' },
        { values: buildings, className: 'column2' },
        { values: units, className: 'column3' },
        { values: floors, className: 'column4' },
        { values: rooms, className: 'column5' }
      ]);

      this.setData({
        showHousePicker: true,
        houseColumns: [
          { values: communities, className: 'column1' },
          { values: buildings, className: 'column2' },
          { values: units, className: 'column3' },
          { values: floors, className: 'column4' },
          { values: rooms, className: 'column5' }
        ]
      });
  
      // 设置默认选中项（每列的第一个）
      picker.setIndexes([0, 0, 0, 0, 0]);
    },
  
  // 关闭房屋选择器
  closeHousePicker() {
    this.setData({ showHousePicker: false });
  },
  
  // 选择器变化事件（多列联动）
  onHousePickerChange(e) {
    const { picker, value, index } = e.detail;
    const { houseTree } = this.data;
    
    // 当前选择的值（可能是数组或单个对象）
    const currentSelection = Array.isArray(value) ? value : [value];

    switch(index) {
      case 0: // 小区变化
        if (currentSelection.length === 0) return;
        
        const communityId = currentSelection[0].value;
        const communityName = Object.keys(houseTree).find(name => 
          houseTree[name].id === communityId
        );
        
        if (!communityName || !houseTree[communityName].buildings) {
          picker.setColumnValues(1, []);
          picker.setColumnValues(2, []);
          picker.setColumnValues(3, []);
          picker.setColumnValues(4, []);
          return;
        }
        
        // 构建楼栋数据
        const buildings = houseTree[communityName].buildings.map(b => ({
          text: b.name,
          value: b.id
        }));
        picker.setColumnValues(1, buildings);
        
        // 自动选择第一栋楼
        if (buildings.length > 0) {
          picker.setColumnIndex(1, 0);
          this.onHousePickerChange({
            detail: {
              picker,
              value: [
                currentSelection[0],
                buildings[0]
              ],
              index: 1
            }
          });
        } else {
          picker.setColumnValues(2, []);
          picker.setColumnValues(3, []);
          picker.setColumnValues(4, []);
        }
        break;
        
      case 1: // 楼栋变化
        if (currentSelection.length < 2) return;
        
        const communityName1 = Object.keys(houseTree).find(name => 
          houseTree[name].id === currentSelection[0].value
        );
        const buildingId = currentSelection[1].value;
        const building = houseTree[communityName1].buildings.find(b => b.id === buildingId);
        
        if (!building || !building.units) {
          picker.setColumnValues(2, []);
          picker.setColumnValues(3, []);
          picker.setColumnValues(4, []);
          return;
        }
        
        // 构建单元数据
        const units = (building.units || []).map(u => ({
          text: u.name,
          value: u.id
        }));
        picker.setColumnValues(2, units);
        
        // 自动选择第一个单元
        if (units.length > 0) {
          picker.setColumnIndex(2, 0);
          this.onHousePickerChange({
            detail: {
              picker,
              value: [
                currentSelection[0],
                currentSelection[1],
                units[0]
              ],
              index: 2
            }
          });
        } else {
          picker.setColumnValues(3, []);
          picker.setColumnValues(4, []);
        }
        break;
        
      case 2: // 单元变化
        if (currentSelection.length < 3) return;
        
        const communityName2 = Object.keys(houseTree).find(name => 
          houseTree[name].id === currentSelection[0].value
        );
        const buildingId2 = currentSelection[1].value;
        const building2 = houseTree[communityName2].buildings.find(b => b.id === buildingId2);
        const unitId = currentSelection[2].value;
        const unit = building2.units.find(u => u.id === unitId);
        
        if (!unit || !unit.floors) {
          picker.setColumnValues(3, []);
          picker.setColumnValues(4, []);
          return;
        }
        
        // 构建楼层数据
        const floors = (unit.floors || []).map(f => ({
          text: f.name,
          value: f.id
        }));
        picker.setColumnValues(3, floors);
        
        // 自动选择第一个楼层
        if (floors.length > 0) {
          picker.setColumnIndex(3, 0);
          this.onHousePickerChange({
            detail: {
              picker,
              value: [
                currentSelection[0],
                currentSelection[1],
                currentSelection[2],
                floors[0]
              ],
              index: 3
            }
          });
        } else {
          picker.setColumnValues(4, []);
        }
        break;
        
      case 3: // 楼层变化
        if (currentSelection.length < 4) return;
        
        const communityName3 = Object.keys(houseTree).find(name => 
          houseTree[name].id === currentSelection[0].value
        );
        const buildingId3 = currentSelection[1].value;
        const building3 = houseTree[communityName3].buildings.find(b => b.id === buildingId3);
        const unitId3 = currentSelection[2].value;
        const unit3 = building3.units.find(u => u.id === unitId3);
        const floorId = currentSelection[3].value;
        const floor = unit3.floors.find(f => f.id === floorId);
        
        if (!floor || !floor.rooms) {
          picker.setColumnValues(4, []);
          return;
        }
        
        // 构建房间数据
        const rooms = (floor.rooms || []).map(r => ({
          text: r.name,
          value: r.id
        }));
        picker.setColumnValues(4, rooms);
        
        // 自动选择第一个房间
        if (rooms.length > 0) {
          picker.setColumnIndex(4, 0);
        }
        break;
    }
  },
  
  // 确认房屋选择
  onHousePickerConfirm(e) {
    const { value } = e.detail;
    
    this.setData({
      showHousePicker: false,
      'formData.community': value[0].text,
      'formData.communityId': value[0].value,
      'formData.building': value[1].text,
      'formData.buildingId': value[1].value,
      'formData.unit': value[2].text,
      'formData.unitId': value[2].value,
      'formData.floor': value[3].text,
      'formData.floorId': value[3].value,
      'formData.room': value[4].text,
      'formData.houseId': value[4].value,
    });
    console.log(this.data.formData)
  },

  // 优化后的buildHouseTree函数
  buildHouseTree(data) {
    if (!Array.isArray(data)) {
      console.warn('buildHouseTree: 数据不是数组', data);
      return {};
    }

    // 创建映射表
    const nodeMap = {};
    data.forEach(item => {
      if (item && item.id) {
        nodeMap[item.id] = {
          ...item,
          children: [],
          name: item.name || ''
        };
      }
    });

    // 构建父子关系
    data.forEach(item => {
      if (item && item.parentId && nodeMap[item.parentId]) {
        nodeMap[item.parentId].children.push(nodeMap[item.id]);
      }
    });

    // 创建社区树
    const communityTree = {};
    data.forEach(item => {
      if (item.type === "1") { // 小区节点
        const communityNode = nodeMap[item.id];
        
        // 初始化社区结构
        communityTree[communityNode.name] = {
          id: communityNode.id,
          name: communityNode.name,
          buildings: []
        };
        
        // 处理楼栋
        communityNode.children.forEach(buildingNode => {
          if (buildingNode.type === "2") {
            const building = {
              id: buildingNode.id,
              name: buildingNode.name,
              units: []
            };
            
            // 处理单元
            buildingNode.children.forEach(unitNode => {
              if (unitNode.type === "3") {
                const unit = {
                  id: unitNode.id,
                  name: unitNode.name,
                  floors: []
                };
                
                // 处理楼层
                unitNode.children.forEach(floorNode => {
                  if (floorNode.type === "4") {
                    const floor = {
                      id: floorNode.id,
                      name: floorNode.name,
                      rooms: []
                    };
                    
                    // 处理房间
                    floorNode.children.forEach(roomNode => {
                      if (roomNode.type === "5") {
                        floor.rooms.push({
                          id: roomNode.id,
                          name: roomNode.name
                        });
                      }
                    });
                    
                    unit.floors.push(floor);
                  }
                });
                
                building.units.push(unit);
              }
            });
            
            communityTree[communityNode.name].buildings.push(building);
          }
        });
      }
    });
    console.log(JSON.stringify(communityTree) )

    return communityTree;
  },

  // 显示证件类型选择器
  showIdTypePicker() {
    this.setData({ showIdType: true })
  },

  // 关闭证件类型选择器
  closeIdTypePicker() {
    this.setData({ showIdType: false })
  },

 // 确认证件类型选择
onIdTypeConfirm(e) {

  const { value } = e.detail; // value 是一个对象，包含 text 和 value 属性
  const selectedOption = this.data.idTypeOptions.find(option => option.value === value.value);

  if (!selectedOption) {
    wx.showToast({
      title: "选择的证件类型无效",
      icon: "none",
    });
    return;
  }

  this.setData({
    "formData.idType": selectedOption.text,
    "formData.idTypeId": selectedOption.value,
    showIdType: false,
  });

  this.checkCanSubmit();
},

  // 显示住户类型选择器
  showResidentTypePicker() {
    this.setData({ showResidentType: true })
  },

  // 关闭住户类型选择器
  closeResidentTypePicker() {
    this.setData({ showResidentType: false })
  },

  // 确认住户类型选择
  onResidentTypeConfirm(e) {
    const  {value}  = e.detail; // value 是一个对象，包含 text 和 value 属性
  const selectedOption = this.data.residentTypeOptions.find(option => option.value === value.value);
  console.log(selectedOption)
    
    this.setData({
      "formData.residentType": selectedOption.text,
      "formData.typeId": selectedOption.value,
      showResidentType: false,
    })
    this.checkCanSubmit()
  },

// 获取住户类型
async getResidentTypeOptions() {
  try {
    const res = await req.get("/property/residentType/list");
    if (res.code === 200) {
      // 提取 rows 数组，并转换为 { text, value } 格式
      const residentTypeOptions = res.rows.map(item => ({
        text: item.type, // 展示的文本
        value: item.id   // 对应的 ID
      }));

      // 更新页面数据
      this.setData({
        residentTypeOptions: residentTypeOptions
      });

      console.log("住户类型获取成功:", residentTypeOptions);
    } else {
      console.error("获取住户类型失败:", res.msg);
      wx.showToast({
        title: `获取住户类型失败: ${res.msg}`,
        icon: "none"
      });
    }
  } catch (error) {
    console.error("请求住户类型时发生错误:", error);
    wx.showToast({
      title: "请求住户类型时发生错误",
      icon: "none"
    });
  }
},

// 获取证件类型
async getIdTypeOptions() {
  try {
    const res = await req.get("/property/idType/list");
    if (res.code === 200) {
      // 提取 rows 数组，并转换为 { text, value } 格式
      const idTypeOptions = res.rows.map(item => ({
        text: item.idType, // 展示的文本
        value: item.id   // 对应的 ID
      }));

      // 更新页面数据
      this.setData({
        idTypeOptions: idTypeOptions
      });

      console.log("住户类型获取成功:", idTypeOptions);
    } else {
      console.error("获取住户类型失败:", res.msg);
      wx.showToast({
        title: `获取住户类型失败: ${res.msg}`,
        icon: "none"
      });
    }
  } catch (error) {
    console.error("请求住户类型时发生错误:", error);
    wx.showToast({
      title: "请求住户类型时发生错误",
      icon: "none"
    });
  }
},

checkCanSubmit() {
  const { formData } = this.data;
  const required = [
    "houseId", "name", "phone",
    "idTypeId", "idNumber", "typeId", "image"
  ];

  const isFormValid = required.every((field) => {
    const value = formData[field];
    if (!value || value.trim() === "") {
      console.log(`字段 ${field} 不符合要求，值为:`, value);
      return false;
    }
    return true;
  });

  this.setData({
    canSubmit: isFormValid,
  });
  console.log("formData:", formData);
},

  // 表单验证
  validateForm() {
    return true
  },

  // 提交表单
  async onSubmit() {
    if (!this.data.canSubmit) {
      wx.showToast({
        title: "请完善必填信息",
        icon: "none",
      })
      return
    }

    if (!this.validateForm()) {
      return
    }

    this.setData({ submitting: true })

    // 准备提交数据
    const submitData = {
      name: this.data.formData.name,
      phone: this.data.formData.phone,
      idTypeId: this.data.formData.idTypeId,
      idNumber: this.data.formData.idNumber,
      houseId: this.data.formData.houseId,
      image: this.data.formData.image,
      status: 2,  // 状态正常
      typeId: this.data.formData.typeId  // 暂时留空
    };
    
    try {
      // 实际提交操作
      await req.post("/property/resident/bindHouse", submitData);
      
      wx.showToast({
        title: "提交成功",
        icon: "success",
        duration: 1500
      });
      
      // 返回上一页并刷新
      setTimeout(() => {
        const pages = getCurrentPages();
        if (pages.length > 1) {
          const prevPage = pages[pages.length - 2];
          if (prevPage && prevPage.loadHouses) {
            prevPage.loadHouses();
          }
          wx.navigateBack();
        }
      }, 1500);
    } catch (e) {
      wx.showToast({
        title: "提交失败: " + (e.message || "网络错误"),
        icon: "none"
      });
    } finally {
      this.setData({ submitting: false });
    }
  },
})